#include <stdio.h>
#include <stdlib.h>

// 定义堆栈的结构体
typedef struct Stack {
    int top;
    unsigned capacity;
    int array[100];
} Stack;

// 初始化栈
Stack* createStack(unsigned capacity) {
    Stack* stack = (Stack*)malloc(sizeof(Stack));
    if (stack == NULL) {
        return NULL;
    }
    stack->capacity = capacity;
    stack->top = -1;
    // stack->array = (int*)malloc(stack->capacity * sizeof(int));
    // if (stack->array == NULL) {
    //     free(stack);
    //     return NULL;
    // }
    return stack;
}

// 判断栈是否为空
int isEmpty(Stack* stack) {
    return stack->top == -1;
}

// 入栈操作
int push(Stack* stack, int item) {
    if (stack->top >= stack->capacity - 1) {
        return 0; // 栈满，无法入栈
    }
    stack->array[++stack->top] = item;
    return 1;
}

// 出栈操作
int pop(Stack* stack, int* item) {
    if (isEmpty(stack)) {
        return 0; // 栈空，无法出栈
    }
    *item = stack->array[stack->top--];
    return 1;
}

// 返回栈顶元素
int topElement(Stack* stack, int* item) {
    if (isEmpty(stack)) {
        return 0; // 栈空，无法获取栈顶元素
    }
    *item = stack->array[stack->top];
    return 1;
}

// 销毁栈
void deleteStack(Stack** stack) {
    // free((*stack)->array);
    free(*stack);
    *stack = NULL;
}

int main() {
    // 测试堆栈操作
    unsigned capacity = 5;
    Stack* stack = createStack(capacity);

    if (!stack) {
        printf("Stack creation failed\n");
        return EXIT_FAILURE;
    }

    // 入栈操作
    push(stack, 10);
    push(stack, 20);
    push(stack, 30);

    // 获取栈顶元素
    int top;
    if (topElement(stack, &top)) {
        printf("Top element is %d\n", top);
    }

    // 出栈操作
    int item;
    if (pop(stack, &item)) {
        printf("Popped item is %d\n", item);
    }

    // 销毁栈
    deleteStack(&stack);

    return 0;
}
